import React, {
  useState,
  useEffect,
  useMemo,
  useCallback,
  useRef,
} from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Plus,
  Trash2,
  Save,
  X,
  Settings,
  Shield,
  Wrench,
  Users,
  Package,
  Truck,
  BookText,
  RefreshCw,
  Check,
  ChevronsUpDown,
  GitCommit,
  AlertTriangle,
} from "lucide-react";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { StandardAPI } from "@/api/Standard";
import { DocumentTemplateAPI } from "@/api/DocumentTemplate";
import { EmergencyMeasureTemplateAPI } from "@/api/EmergencyMeasureTemplate";
import { SafetyRiskPointAPI } from "@/api/SafetyRiskPoint";
import { useToast } from "@/components/ui/use-toast";

// 自动调整高度的Textarea组件
const AutoResizingTextarea = ({
  value,
  onChange,
  placeholder,
  minRows = 2,
  ...props
}) => {
  const textareaRef = useRef(null);

  // 调整文本框高度
  const adjustHeight = () => {
    if (textareaRef.current) {
      // 重置高度以获取正确的滚动高度
      textareaRef.current.style.height = "auto";
      // 计算所需高度（至少为minRows的高度）
      const scrollHeight = textareaRef.current.scrollHeight;
      const lineHeight = 24; // 估算行高，可根据实际情况调整
      const minHeight = minRows * lineHeight;
      const newHeight = Math.max(scrollHeight, minHeight);

      textareaRef.current.style.height = `${newHeight}px`;
    }
  };

  // 初始渲染和值变化时调整高度
  useEffect(() => {
    adjustHeight();
  }, [value]);

  return (
    <Textarea
      ref={textareaRef}
      value={value || ""}
      onChange={onChange}
      placeholder={placeholder}
      rows={minRows}
      style={{
        resize: "none", // 禁用手动调整大小
        overflow: "hidden", // 隐藏滚动条
      }}
      {...props}
    />
  );
};

// 自动调整文本框高度的工具函数
const autoResize = (textarea) => {
  if (!textarea) return;
  textarea.style.height = "auto";
  textarea.style.height = `${textarea.scrollHeight + 2}px`;
};

// 物料表格编辑器（新样式）
const MaterialsTableEditor = ({ items = [], onUpdate }) => {
  const safeItems = Array.isArray(items) ? items : [];

  const handleAddItem = () => {
    const newItem = { name: "", specification: "", unit: "", quantity: 1 };
    onUpdate([...safeItems, newItem]);
  };

  const handleUpdateItem = (index, field, value) => {
    const newItems = [...safeItems];
    
    if (field === "quantity") {
      const numValue = parseInt(value) || 0;
      newItems[index][field] = Math.max(1, numValue);
    } else {
      newItems[index][field] = value;
    }
    
    onUpdate(newItems);
  };

  const handleRemoveItem = (index) => {
    onUpdate(safeItems.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
      <div className="bg-blue-50 border border-blue-200 rounded-md p-3">
        <div className="flex items-start">
          <div className="flex-shrink-0">
            <svg className="w-5 h-5 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
            </svg>
          </div>
          <div className="ml-3">
            <p className="text-sm text-blue-700">
              物料数量必须大于0，最小值自动设置为1
            </p>
          </div>
        </div>
      </div>

      <div className="flex items-center justify-between">
        <h4 className="font-medium text-gray-800 flex items-center gap-2">
          <Package className="w-4 h-4" />
          所需物料
        </h4>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={handleAddItem}
          className="bg-white"
        >
          <Plus className="w-4 h-4 mr-1" /> 添加
        </Button>
      </div>
      
      {safeItems.length > 0 ? (
        <div className="overflow-x-auto border border-gray-200 rounded-md">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b">
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">名称</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">规格</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">单位</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">数量 *</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">操作</th>
              </tr>
            </thead>
            <tbody>
              {safeItems.map((item, index) => (
                <tr key={index} className="border-b hover:bg-gray-50">
                  <td className="px-3 py-2">
                    <Input
                      value={item.name || ""}
                      onChange={(e) => handleUpdateItem(index, "name", e.target.value)}
                      placeholder="物料名称"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      value={item.specification || ""}
                      onChange={(e) => handleUpdateItem(index, "specification", e.target.value)}
                      placeholder="规格型号"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      value={item.unit || ""}
                      onChange={(e) => handleUpdateItem(index, "unit", e.target.value)}
                      placeholder="单位"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      type="number"
                      min="1"
                      value={item.quantity || 1}
                      onChange={(e) => handleUpdateItem(index, "quantity", e.target.value)}
                      placeholder="数量"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        handleRemoveItem(index);
                      }}
                      className="text-red-500 hover:text-red-700 h-8 w-8"
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="text-center py-8 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg">
          <Package className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p>暂无物料数据</p>
        </div>
      )}
    </div>
  );
};

// 人员表格编辑器（新样式）
const PersonnelTableEditor = ({ items = [], onUpdate }) => {
  const safeItems = Array.isArray(items) ? items : [];

  const handleAddItem = () => {
    const newItem = { role: "", quantity: 1, qualification: "" };
    onUpdate([...safeItems, newItem]);
  };

  const handleUpdateItem = (index, field, value) => {
    const newItems = [...safeItems];
    
    if (field === "quantity") {
      const numValue = parseInt(value) || 0;
      newItems[index][field] = Math.max(1, numValue);
    } else {
      newItems[index][field] = value;
    }
    
    onUpdate(newItems);
  };

  const handleRemoveItem = (index) => {
    onUpdate(safeItems.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
      <div className="bg-blue-50 border border-blue-200 rounded-md p-3">
        <div className="flex items-start">
          <div className="flex-shrink-0">
            <svg className="w-5 h-5 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
            </svg>
          </div>
          <div className="ml-3">
            <p className="text-sm text-blue-700">
              人员数量必须大于0，最小值自动设置为1
            </p>
          </div>
        </div>
      </div>

      <div className="flex items-center justify-between">
        <h4 className="font-medium text-gray-800 flex items-center gap-2">
          <Users className="w-4 h-4" />
          所需人员
        </h4>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={handleAddItem}
          className="bg-white"
        >
          <Plus className="w-4 h-4 mr-1" /> 添加
        </Button>
      </div>
      
      {safeItems.length > 0 ? (
        <div className="overflow-x-auto border border-gray-200 rounded-md">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b">
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">岗位角色</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">资质要求</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">人数 *</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">操作</th>
              </tr>
            </thead>
            <tbody>
              {safeItems.map((item, index) => (
                <tr key={index} className="border-b hover:bg-gray-50">
                  <td className="px-3 py-2">
                    <Input
                      value={item.role || ""}
                      onChange={(e) => handleUpdateItem(index, "role", e.target.value)}
                      placeholder="岗位角色"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      value={item.qualification || ""}
                      onChange={(e) => handleUpdateItem(index, "qualification", e.target.value)}
                      placeholder="资质要求"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      type="number"
                      min="1"
                      value={item.quantity || 1}
                      onChange={(e) => handleUpdateItem(index, "quantity", e.target.value)}
                      placeholder="人数"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        handleRemoveItem(index);
                      }}
                      className="text-red-500 hover:text-red-700 h-8 w-8"
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="text-center py-8 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg">
          <Users className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p>暂无人员数据</p>
        </div>
      )}
    </div>
  );
};

// 工器具表格编辑器（新样式）
const EquipmentTableEditor = ({ items = [], onUpdate }) => {
  const safeItems = Array.isArray(items) ? items : [];

  const handleAddItem = () => {
    const newItem = { name: "", specification: "", unit: "", quantity: 1 };
    onUpdate([...safeItems, newItem]);
  };

  const handleUpdateItem = (index, field, value) => {
    const newItems = [...safeItems];
    
    if (field === "quantity") {
      const numValue = parseInt(value) || 0;
      newItems[index][field] = Math.max(1, numValue);
    } else {
      newItems[index][field] = value;
    }
    
    onUpdate(newItems);
  };

  const handleRemoveItem = (index) => {
    onUpdate(safeItems.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
      <div className="bg-blue-50 border border-blue-200 rounded-md p-3">
        <div className="flex items-start">
          <div className="flex-shrink-0">
            <svg className="w-5 h-5 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
            </svg>
          </div>
          <div className="ml-3">
            <p className="text-sm text-blue-700">
              工器具数量必须大于0，最小值自动设置为1
            </p>
          </div>
        </div>
      </div>

      <div className="flex items-center justify-between">
        <h4 className="font-medium text-gray-800 flex items-center gap-2">
          <Wrench className="w-4 h-4" />
          所需工器具
        </h4>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={handleAddItem}
          className="bg-white"
        >
          <Plus className="w-4 h-4 mr-1" /> 添加
        </Button>
      </div>
      
      {safeItems.length > 0 ? (
        <div className="overflow-x-auto border border-gray-200 rounded-md">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b">
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">名称</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">规格</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">单位</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">数量 *</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">操作</th>
              </tr>
            </thead>
            <tbody>
              {safeItems.map((item, index) => (
                <tr key={index} className="border-b hover:bg-gray-50">
                  <td className="px-3 py-2">
                    <Input
                      value={item.name || ""}
                      onChange={(e) => handleUpdateItem(index, "name", e.target.value)}
                      placeholder="工器具名称"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      value={item.specification || ""}
                      onChange={(e) => handleUpdateItem(index, "specification", e.target.value)}
                      placeholder="规格型号"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      value={item.unit || ""}
                      onChange={(e) => handleUpdateItem(index, "unit", e.target.value)}
                      placeholder="单位"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      type="number"
                      min="1"
                      value={item.quantity || 1}
                      onChange={(e) => handleUpdateItem(index, "quantity", e.target.value)}
                      placeholder="数量"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        handleRemoveItem(index);
                      }}
                      className="text-red-500 hover:text-red-700 h-8 w-8"
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="text-center py-8 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg">
          <Wrench className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p>暂无工器具数据</p>
        </div>
      )}
    </div>
  );
};

// 车辆表格编辑器（新样式）
const VehiclesTableEditor = ({ items = [], onUpdate }) => {
  const safeItems = Array.isArray(items) ? items : [];

  const handleAddItem = () => {
    const newItem = { type: "", licensePlate: "", quantity: 1 };
    onUpdate([...safeItems, newItem]);
  };

  const handleUpdateItem = (index, field, value) => {
    const newItems = [...safeItems];
    
    if (field === "quantity") {
      const numValue = parseInt(value) || 0;
      newItems[index][field] = Math.max(1, numValue);
    } else {
      newItems[index][field] = value;
    }
    
    onUpdate(newItems);
  };

  const handleRemoveItem = (index) => {
    onUpdate(safeItems.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
      <div className="bg-blue-50 border border-blue-200 rounded-md p-3">
        <div className="flex items-start">
          <div className="flex-shrink-0">
            <svg className="w-5 h-5 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
            </svg>
          </div>
          <div className="ml-3">
            <p className="text-sm text-blue-700">
              车辆数量必须大于0，最小值自动设置为1
            </p>
          </div>
        </div>
      </div>

      <div className="flex items-center justify-between">
        <h4 className="font-medium text-gray-800 flex items-center gap-2">
          <Truck className="w-4 h-4" />
          所需车辆
        </h4>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={handleAddItem}
          className="bg-white"
        >
          <Plus className="w-4 h-4 mr-1" /> 添加
        </Button>
      </div>
      
      {safeItems.length > 0 ? (
        <div className="overflow-x-auto border border-gray-200 rounded-md">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 border-b">
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">车辆类型</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">车牌号（可选）</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">数量 *</th>
                <th className="px-3 py-2 text-left text-sm font-medium text-gray-700">操作</th>
              </tr>
            </thead>
            <tbody>
              {safeItems.map((item, index) => (
                <tr key={index} className="border-b hover:bg-gray-50">
                  <td className="px-3 py-2">
                    <Input
                      value={item.type || ""}
                      onChange={(e) => handleUpdateItem(index, "type", e.target.value)}
                      placeholder="车辆类型"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      value={item.licensePlate || ""}
                      onChange={(e) => handleUpdateItem(index, "licensePlate", e.target.value)}
                      placeholder="车牌号（可选）"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Input
                      type="number"
                      min="1"
                      value={item.quantity || 1}
                      onChange={(e) => handleUpdateItem(index, "quantity", e.target.value)}
                      placeholder="数量"
                      className="border-0 focus-visible:ring-1 focus-visible:ring-blue-500"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        handleRemoveItem(index);
                      }}
                      className="text-red-500 hover:text-red-700 h-8 w-8"
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="text-center py-8 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg">
          <Truck className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p>暂无车辆数据</p>
        </div>
      )}
    </div>
  );
};
// 字符串数组编辑器
const StringArrayEditor = ({ title, items = [], onUpdate, placeholder }) => {
  const safeItems = Array.isArray(items) ? items : [];

  const handleAddItem = () => {
    onUpdate([...safeItems, ""]);
  };

  const handleUpdateItem = (index, value) => {
    const newItems = [...safeItems];
    newItems[index] = value;
    onUpdate(newItems);
  };

  const handleRemoveItem = (index) => {
    onUpdate(safeItems.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
      <h4 className="font-medium text-gray-800">{title}</h4>
      <div className="space-y-2">
        {safeItems.map((item, index) => (
          <div key={`${title}-item-${index}`} className="flex items-center gap-2">
            <Input
              value={item}
              onChange={(e) => handleUpdateItem(index, e.target.value)}
              placeholder={placeholder || `请输入条目 ${index + 1}`}
            />
            <Button
              type="button"
              variant="ghost"
              size="icon"
              onClick={(e) => {
                e.stopPropagation();
                e.preventDefault();
                handleRemoveItem(index);
              }}
              className="text-red-500 hover:text-red-700 shrink-0"
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          </div>
        ))}
      </div>
      <Button
        type="button"
        variant="outline"
        size="sm"
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          handleAddItem();
        }}
        className="bg-white"
      >
        <Plus className="w-4 h-4 mr-2" /> 添加条目
      </Button>
    </div>
  );
};

// 工程系数规则编辑器
const EngineeringFactorsEditor = ({ factors = {}, onUpdate }) => {
  const getDefaultFactors = useCallback(
    () => ({
      spanFactorRules: [
        { threshold: 500, multiplier: 1.5 },
        { threshold: 300, multiplier: 1.2 },
        { threshold: 150, multiplier: 1.0 },
        { threshold: 0, multiplier: 0.8 },
      ],
      heightFactorRules: [
        { threshold: 80, multiplier: 1.4 },
        { threshold: 50, multiplier: 1.2 },
        { threshold: 30, multiplier: 1.0 },
        { threshold: 0, multiplier: 0.9 },
      ],
      nettingFactorRules: [
        { threshold: 200, multiplier: 2.0 },
        { threshold: 150, multiplier: 1.5 },
        { threshold: 100, multiplier: 1.0 },
        { threshold: 50, multiplier: 0.8 },
        { threshold: 0, multiplier: 0.5 },
      ],
      angleFactorRules: [
        { threshold: 60, multiplier: 1.3 },
        { threshold: 75, multiplier: 1.1 },
        { threshold: 90, multiplier: 1.0 },
      ],
      widthFactorRules: [
        { threshold: 50, multiplier: 1.4 },
        { threshold: 20, multiplier: 1.2 },
        { threshold: 10, multiplier: 1.0 },
        { threshold: 0, multiplier: 0.8 },
      ],
      typeFactorMultipliers: [
        { type: "highwayExpressway", multiplier: 1.5 },
        { type: "highwayGradePlus2", multiplier: 1.3 },
        { type: "railwayHighSpeed", multiplier: 1.6 },
        { type: "railwayNormal", multiplier: 1.4 },
        { type: "riverNavigable", multiplier: 1.2 },
        { type: "powerLineOutagePlus500", multiplier: 1.8 },
        { type: "powerLineOutagePlus110", multiplier: 1.7 },
        { type: "powerLineOutagePlus10", multiplier: 1.6 },
        { type: "other", multiplier: 1.0 },
      ],
    }),
    []
  );

  const [currentFactors, setCurrentFactors] = useState({});

  useEffect(() => {
    const defaultFactors = getDefaultFactors();
    const mergedFactors = {};
    let isInitialLoadWithEmptyFactors = true;

    Object.keys(defaultFactors).forEach((key) => {
      if (
        factors &&
        factors[key] &&
        Array.isArray(factors[key]) &&
        factors[key].length > 0
      ) {
        mergedFactors[key] = factors[key];
        isInitialLoadWithEmptyFactors = false;
      } else {
        mergedFactors[key] = defaultFactors[key];
      }
    });

    setCurrentFactors(mergedFactors);

    if (isInitialLoadWithEmptyFactors) {
      onUpdate(mergedFactors);
    }
  }, [factors, onUpdate, getDefaultFactors]);

  const updateFactorRule = useCallback(
    (category, index, field, value) => {
      setCurrentFactors((prevFactors) => {
        const newFactors = { ...prevFactors };
        if (!newFactors[category]) {
          newFactors[category] = [];
        }

        const newRules = [...newFactors[category]];
        if (field === "threshold" || field === "multiplier") {
          newRules[index] = {
            ...newRules[index],
            [field]: parseFloat(value) || 0,
          };
        } else {
          newRules[index] = { ...newRules[index], [field]: value };
        }

        newFactors[category] = newRules;
        onUpdate(newFactors);
        return newFactors;
      });
    },
    [onUpdate]
  );

  const addFactorRule = useCallback(
    (category) => {
      setCurrentFactors((prevFactors) => {
        const newFactors = { ...prevFactors };
        if (!newFactors[category]) {
          newFactors[category] = [];
        }

        const newRule =
          category === "typeFactorMultipliers"
            ? { type: "", multiplier: 1.0 }
            : { threshold: 0, multiplier: 1.0 };

        newFactors[category] = [...newFactors[category], newRule];
        onUpdate(newFactors);
        return newFactors;
      });
    },
    [onUpdate]
  );

  const removeFactorRule = useCallback(
    (category, index) => {
      setCurrentFactors((prevFactors) => {
        const newFactors = { ...prevFactors };
        if (newFactors[category] && newFactors[category].length > 1) {
          newFactors[category] = newFactors[category].filter(
            (_, i) => i !== index
          );
          onUpdate(newFactors);
          return newFactors;
        }
        return prevFactors;
      });
    },
    [onUpdate]
  );

  const resetToDefaults = useCallback(() => {
    const defaultFactors = getDefaultFactors();
    setCurrentFactors(defaultFactors);
    onUpdate(defaultFactors);
  }, [onUpdate, getDefaultFactors]);

  const FactorRuleEditor = React.memo(
    ({ title, category, rules, isTypeRule = false, description }) => (
      <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
        <div className="flex items-center justify-between">
          <div>
            <h4 className="font-medium text-gray-800">{title}</h4>
            <p className="text-sm text-gray-600 mt-1">{description}</p>
          </div>
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={() => addFactorRule(category)}
            className="bg-white"
          >
            <Plus className="w-4 h-4 mr-2" />
            添加规则
          </Button>
        </div>

        <div className="space-y-2">
          {rules &&
            rules.map((rule, index) => (
              <div
                key={`${category}-${index}`}
                className="flex items-center gap-2 p-2 bg-white rounded border"
              >
                {isTypeRule ? (
                  <>
                    <select
                      value={rule.type || ""}
                      onChange={(e) =>
                        updateFactorRule(
                          category,
                          index,
                          "type",
                          e.target.value
                        )
                      }
                      className="flex-1 px-2 py-1 border rounded text-sm h-9"
                    >
                      <option value="powerLineOutagePlus500">
                        跨越电力线路（带电）
                      </option>
                      <option value="powerLineOutagePlus110">
                        跨越电力线路（不带电）
                      </option>
                      <option value="railway">跨越普通铁路</option>
                      <option value="railwayHighSpeed">跨越高铁</option>
                      <option value="firstHighway">
                        跨越高速公路(含全封闭一级公路)
                      </option>
                      <option value="highwayGradePlus2">
                        跨越公路(二级及以下公路)
                      </option>
                      <option value="navigableRivers">跨越通航河流</option>
                      <option value="noNavigableRivers">跨越不通航河流</option>
                      <option value="railwayNormal">跨越通信线路</option>
                      <option value="other">其它</option>
                    </select>
                    <span className="text-sm text-gray-500 whitespace-nowrap">
                      系数:
                    </span>
                  </>
                ) : (
                  <>
                    <span className="text-sm text-gray-500 whitespace-nowrap">
                      {category.includes("angle") ? "< " : "≥ "}
                    </span>
                    <Input
                      type="number"
                      step="0.1"
                      value={rule.threshold || 0}
                      onChange={(e) =>
                        updateFactorRule(
                          category,
                          index,
                          "threshold",
                          e.target.value
                        )
                      }
                      className="w-24 text-sm"
                      placeholder="阈值"
                    />
                    <span className="text-sm text-gray-500">系数:</span>
                  </>
                )}
                <Input
                  type="number"
                  step="0.1"
                  value={rule.multiplier || 1.0}
                  onChange={(e) =>
                    updateFactorRule(
                      category,
                      index,
                      "multiplier",
                      e.target.value
                    )
                  }
                  className="w-20 text-sm"
                  placeholder="1.0"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  onClick={(e) => {
                    e.stopPropagation();
                    e.preventDefault();
                    removeFactorRule(category, index);
                  }}
                  className="text-red-500 hover:text-red-700 shrink-0"
                  disabled={rules.length <= 1}
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            ))}
        </div>
      </div>
    )
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold">工程系数规则配置</h3>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={resetToDefaults}
          className="bg-blue-50 border-blue-200 text-blue-700 hover:bg-blue-100"
        >
          <RefreshCw className="w-4 h-4 mr-2" />
          恢复默认值
        </Button>
      </div>

      <FactorRuleEditor
        title="跨越档距系数"
        category="spanFactorRules"
        rules={currentFactors.spanFactorRules}
        description="根据跨越档距长度确定施工难度系数"
      />

      <FactorRuleEditor
        title="跨越高度系数"
        category="heightFactorRules"
        rules={currentFactors.heightFactorRules}
        description="根据跨越高度确定施工难度系数"
      />

      <FactorRuleEditor
        title="封网长度系数"
        category="nettingFactorRules"
        rules={currentFactors.nettingFactorRules}
        description="根据封网长度确定材料用量系数"
      />

      <FactorRuleEditor
        title="交叉角度系数"
        category="angleFactorRules"
        rules={currentFactors.angleFactorRules}
        description="根据与被跨越物的交叉角度确定施工难度系数"
      />

      <FactorRuleEditor
        title="跨越宽度系数"
        category="widthFactorRules"
        rules={currentFactors.widthFactorRules}
        description="根据被跨越物宽度确定施工难度系数"
      />

      <FactorRuleEditor
        title="跨越类型系数"
        category="typeFactorMultipliers"
        rules={currentFactors.typeFactorMultipliers}
        isTypeRule={true}
        description="根据不同的跨越类型确定基础系数"
      />
    </div>
  );
};

// 简化步骤卡片
const CompactStepCard = React.memo(({ step, index, onEdit, onRemove }) => {
  const totalMeasures =
    (step.technicalMeasures?.length || 0) +
    (step.safetyMeasures?.length || 0) +
    (step.qualityMeasures?.length || 0) +
    (step.environmentalMeasures?.length || 0);

  const totalResources =
    (step.requiredMaterials?.length || 0) +
    (step.requiredPersonnel?.length || 0) +
    (step.requiredEquipment?.length || 0) +
    (step.requiredVehicles?.length || 0);

  const predecessorText =
    step.predecessorsStep && step.predecessorsStep.length > 0
      ? `依赖: ${step.predecessorsStep
          .map((order) => `步骤 ${order}`)
          .join(", ")}`
      : "无依赖";

  const associatedRisksCount = step.associatedRiskCodes?.length || 0;

  return (
    <Card
      className="border-l-4 border-l-blue-500 hover:shadow-md transition-shadow cursor-pointer group"
      onClick={() => onEdit(index)}
    >
      <CardContent className="p-4">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <div className="w-8">
              <span className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center text-sm font-bold text-blue-600">
                {step.stepOrder}
              </span>
            </div>

            <div>
              <h4 className="font-semibold text-gray-900">
                {step.stepName || `步骤 ${step.stepOrder}`}
              </h4>
              <div className="text-sm text-gray-500 break-words whitespace-normal max-w-full line-clamp-1">
                {step.description || "暂无描述"}
              </div>
            </div>
          </div>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            onClick={(e) => {
              e.stopPropagation();
              onRemove(index);
            }}
            className="text-red-500 hover:text-red-700 opacity-0 group-hover:opacity-100 transition-opacity"
          >
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>

        <div className="grid grid-cols-4 gap-4 text-sm">
          <div className="flex items-center gap-2">
            <div className="w-6 h-6 bg-green-100 rounded-full flex items-center justify-center">
              <span className="text-xs font-bold text-green-600">
                {step.durationDays || 0}
              </span>
            </div>
            <span className="text-gray-600">天</span>
          </div>

          <div className="flex items-center gap-2">
            <GitCommit className="w-4 h-4 text-cyan-500" />
            <span className="text-gray-600">{predecessorText}</span>
          </div>

          <div className="flex items-center gap-2">
            <Shield className="w-4 h-4 text-orange-500" />
            <span className="text-gray-600">{totalMeasures} 项措施</span>
          </div>

          <div className="flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-red-500" />
            <span className="text-gray-600">
              {associatedRisksCount} 项风险点
            </span>
          </div>
        </div>
      </CardContent>
    </Card>
  );
});

// 详细步骤编辑器
const DetailedStepEditor = React.memo(
  ({
    step,
    index,
    allSteps,
    onUpdate,
    onRemove,
    availableRisks,
    onFinishEditing,
  }) => {
    const [predecessorPopoverOpen, setPredecessorPopoverOpen] = useState(false);
    const [categoryPopoverOpen, setCategoryPopoverOpen] = useState(false);
    const [activeTab, setActiveTab] = useState("technical");
    const textareaRef = useRef(null);

    const handleDescriptionChange = (e) => {
      const value = e.target.value;
      handleFieldUpdate("description", value);
      autoResize(textareaRef.current);
    };

    useEffect(() => {
      autoResize(textareaRef.current);
    }, [step.description]);

    const handleFieldUpdate = useCallback(
      (field, value) => {
        onUpdate(index, field, value);
      },
      [onUpdate, index]
    );

    const selectedPredecessorOrders = useMemo(
      () =>
        new Set(
          (Array.isArray(step.predecessorsStep)
            ? step.predecessorsStep
            : []
          ).map(Number)
        ),
      [step.predecessorsStep]
    );

    const availablePredecessorSteps = useMemo(() => {
      return allSteps
        .filter((s) => s.stepOrder !== step.stepOrder)
        .sort((a, b) => a.stepOrder - b.stepOrder);
    }, [allSteps, step.stepOrder]);

    const handlePredecessorChange = useCallback(
      (stepOrder) => {
        const numericStepOrder = Number(stepOrder);

        const newSelected = new Set(selectedPredecessorOrders);
        if (newSelected.has(numericStepOrder)) {
          newSelected.delete(numericStepOrder);
        } else {
          newSelected.add(numericStepOrder);
        }
        handleFieldUpdate(
          "predecessorsStep",
          Array.from(newSelected).sort((a, b) => a - b)
        );
      },
      [selectedPredecessorOrders, handleFieldUpdate]
    );

    const selectedPredecessorStepsDisplay = useMemo(() => {
      const predecessors = Array.isArray(step.predecessorsStep)
        ? step.predecessorsStep
        : [];

      const validUniquePredecessors = [...new Set(predecessors)].filter(
        (stepOrder) => allSteps.some((s) => s.stepOrder == stepOrder)
      );

      return (
        validUniquePredecessors
          .map((stepOrder) => {
            const stepInfo = allSteps.find((s) => s.stepOrder == stepOrder);
            return `步骤 ${stepInfo.stepOrder} (${
              stepInfo.stepName || "未命名"
            })`;
          })
          .join(", ") || "无前置步骤"
      );
    }, [step.predecessorsStep, allSteps]);

    const availableCategories = useMemo(() => {
      const categories = new Map();
      (availableRisks || []).forEach((risk) => {
        if (
          risk.primaryCategory &&
          risk.secondaryCategory &&
          risk.tertiaryCategory
        ) {
          const key = risk.tertiaryCategory;
          if (!categories.has(key)) {
            categories.set(
              key,
              `${risk.primaryCategory} > ${risk.secondaryCategory} > ${risk.tertiaryCategory}`
            );
          }
        }
      });
      return Array.from(categories.entries()).map(([value, label]) => ({
        value,
        label,
      }));
    }, [availableRisks]);

    const selectedCategories = useMemo(
      () => new Set(step.standardWorkCategories || []),
      [step.standardWorkCategories]
    );

    const handleCategoryChange = useCallback(
      (categoryValue) => {
        const newSelectedCategories = new Set(selectedCategories);
        if (newSelectedCategories.has(categoryValue)) {
          newSelectedCategories.delete(categoryValue);
        } else {
          newSelectedCategories.add(categoryValue);
        }
        const updatedCategoriesArray = Array.from(newSelectedCategories);
        handleFieldUpdate("standardWorkCategories", updatedCategoriesArray);

        const matchingRiskCodes = new Set();
        (availableRisks || []).forEach((risk) => {
          if (newSelectedCategories.has(risk.tertiaryCategory)) {
            matchingRiskCodes.add(risk.id);
          }
        });

        handleFieldUpdate("associatedRiskCodes", Array.from(matchingRiskCodes));
      },
      [selectedCategories, handleFieldUpdate, availableRisks]
    );

    const handleMeasureUpdate = useCallback(
      (field, items) => {
        onUpdate(index, field, items);
      },
      [onUpdate, index]
    );

    const handleResourceUpdate = useCallback(
      (field, items) => {
        onUpdate(index, field, items);
      },
      [onUpdate, index]
    );

    return (
      <Card className="border-l-4 border-l-green-500">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg flex items-center gap-2">
              <span className="w-6 h-6 bg-green-100 rounded-full flex items-center justify-center text-sm font-bold text-green-600">
                {step.stepOrder}
              </span>
              步骤 {step.stepOrder} - 编辑模式
            </CardTitle>
            <div className="flex gap-2">
              <Button 
                type="button"
                variant="outline" 
                size="sm" 
                onClick={onFinishEditing}
              >
                完成编辑
              </Button>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  onRemove(index);
                }}
                className="text-red-500 hover:text-red-700"
              >
                <Trash2 className="w-4 h-4" />
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium mb-1">步骤名称</label>
              <Input
                value={step.stepName || ""}
                onChange={(e) => handleFieldUpdate("stepName", e.target.value)}
                placeholder="例如：现场勘察与准备"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">
                预计工期（天）
              </label>
              <Input
                type="number"
                step="0.5"
                value={step.durationDays || 0}
                onChange={(e) =>
                  handleFieldUpdate(
                    "durationDays",
                    parseFloat(e.target.value) || 0
                  )
                }
                placeholder="1"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium mb-1">步骤描述</label>
            <Textarea
              ref={textareaRef}
              value={step.description || ""}
              onChange={handleDescriptionChange}
              placeholder="详细描述该步骤的具体内容和要求..."
              rows={2}
              style={{
                minHeight: "60px",
                resize: "none",
                overflow: "hidden",
              }}
            />
          </div>

          <Tabs
            value={activeTab}
            onValueChange={setActiveTab}
            className="w-full"
          >
            <TabsList className="grid w-full grid-cols-5">
              <TabsTrigger value="technical">技术</TabsTrigger>
              <TabsTrigger value="safety">安全</TabsTrigger>
              <TabsTrigger value="quality">质量</TabsTrigger>
              <TabsTrigger value="environmental">环保</TabsTrigger>
              <TabsTrigger value="resources">资源</TabsTrigger>
            </TabsList>

            <TabsContent value="technical" className="space-y-4">
              <StringArrayEditor
                title="技术措施"
                items={step.technicalMeasures || []}
                onUpdate={(value) =>
                  handleMeasureUpdate("technicalMeasures", value)
                }
                placeholder="例如：GPS定位确定飞行路径"
              />
            </TabsContent>

            <TabsContent value="safety" className="space-y-4">
              <StringArrayEditor
                title="安全措施"
                items={step.safetyMeasures || []}
                onUpdate={(value) =>
                  handleMeasureUpdate("safetyMeasures", value)
                }
                placeholder="例如：设置安全警戒区域"
              />
            </TabsContent>

            <TabsContent value="quality" className="space-y-4">
              <StringArrayEditor
                title="质量措施"
                items={step.qualityMeasures || []}
                onUpdate={(value) =>
                  handleMeasureUpdate("qualityMeasures", value)
                }
                placeholder="例如：检查设备性能状态"
              />
            </TabsContent>

            <TabsContent value="environmental" className="space-y-4">
              <StringArrayEditor
                title="环保措施"
                items={step.environmentalMeasures || []}
                onUpdate={(value) =>
                  handleMeasureUpdate("environmentalMeasures", value)
                }
                placeholder="例如：控制噪音污染"
              />
            </TabsContent>

            <TabsContent value="resources" className="space-y-4">
              <MaterialsTableEditor
                items={step.requiredMaterials || []}
                onUpdate={(value) => handleResourceUpdate("requiredMaterials", value)}
              />
              <PersonnelTableEditor
                items={step.requiredPersonnel || []}
                onUpdate={(value) => handleResourceUpdate("requiredPersonnel", value)}
              />
              <EquipmentTableEditor
                items={step.requiredEquipment || []}
                onUpdate={(value) => handleResourceUpdate("requiredEquipment", value)}
              />
              <VehiclesTableEditor
                items={step.requiredVehicles || []}
                onUpdate={(value) => handleResourceUpdate("requiredVehicles", value)}
              />
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    );
  }
);

// 施工步骤编辑器
const ConstructionStepsEditor = ({
  steps = [],
  onUpdate,
  availableRisks = [],
}) => {
  const [editingStepIndex, setEditingStepIndex] = useState(null);

  const handleAddStep = useCallback(() => {
    const newStep = {
      stepOrder: steps.length + 1,
      stepName: "",
      description: "",
      durationDays: 1,
      predecessorsStep: [],
      standardWorkCategories: [],
      technicalMeasures: [],
      safetyMeasures: [],
      qualityMeasures: [],
      environmentalMeasures: [],
      requiredMaterials: [],
      requiredPersonnel: [],
      requiredEquipment: [],
      requiredVehicles: [],
      associatedRiskCodes: [],
    };
    const newSteps = [...steps];
    const maxOrder = Math.max(0, ...newSteps.map((s) => s.stepOrder));
    newSteps.push({ ...newStep, stepOrder: maxOrder + 1 });

    onUpdate(newSteps);
    setEditingStepIndex(newSteps.length - 1);
  }, [steps, onUpdate]);

  const handleUpdateStep = useCallback(
    (index, field, value) => {
      const newSteps = [...steps];
      newSteps[index][field] = value;
      onUpdate(newSteps);
    },
    [steps, onUpdate]
  );

  const handleRemoveStep = useCallback(
    (index) => {
      const stepToRemove = steps[index];
      const stepOrderToRemove = stepToRemove.stepOrder;

      const newSteps = steps
        .filter((_, i) => i !== index)
        .map((step) => {
          if (Array.isArray(step.predecessorsStep)) {
            return {
              ...step,
              predecessorsStep: step.predecessorsStep.filter(
                (order) => order !== stepOrderToRemove
              ),
            };
          }
          return step;
        })
        .map((step, i) => ({
          ...step,
          stepOrder: i + 1,
        }));

      onUpdate(newSteps);
      setEditingStepIndex(null);
    },
    [steps, onUpdate]
  );

  const handleEditStep = (index) => {
    setEditingStepIndex(index);
  };

  const handleFinishEditing = () => {
    setEditingStepIndex(null);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="font-semibold text-gray-900">施工步骤配置</h3>
        <div className="flex gap-3">
          <Button
            type="button"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              handleAddStep();
            }}
            variant="outline"
            size="sm"
          >
            <Plus className="w-4 h-4 mr-2" />
            添加步骤
          </Button>
        </div>
      </div>

      <div className="space-y-4">
        {steps.map((step, index) => (
          <div key={`step-${step.stepOrder}-${index}`}>
            {editingStepIndex === index ? (
              <DetailedStepEditor
                key={index}
                step={step}
                index={index}
                allSteps={steps}
                onUpdate={handleUpdateStep}
                onRemove={handleRemoveStep}
                availableRisks={availableRisks}
                onFinishEditing={handleFinishEditing}
              />
            ) : (
              <CompactStepCard
                key={index}
                step={step}
                index={index}
                onEdit={handleEditStep}
                onRemove={handleRemoveStep}
              />
            )}
          </div>
        ))}

        {steps.length === 0 && (
          <div className="text-center py-8 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg">
            <Package className="w-12 h-12 mx-auto mb-4 text-gray-300" />
            <p className="text-lg font-medium mb-2">暂无施工步骤</p>
            <p className="text-sm">点击"添加步骤"开始创建施工方法模板</p>
          </div>
        )}
      </div>
    </div>
  );
};
// 主表单组件
export default function MethodTemplateForm({ template, onSubmit, onCancel }) {
  // 生成基于时间戳的方法代码
  const generateMethodCode = () => {
    const timestamp = Date.now();
    return `method_${timestamp}`;
  };

  const [localTemplate, setLocalTemplate] = useState({});
  const [allStandards, setAllStandards] = useState([]);
  const [documentTemplates, setDocumentTemplates] = useState([]);
  const [emergencyMeasureTemplate, setEmergencyMeasureTemplate] = useState([]);
  const [availableRisks, setAvailableRisks] = useState([]);
  const [emergencyGenResult, setEmergencyGenResult] = useState("");
  const { toast } = useToast();

  useEffect(() => {
    const loadRisks = async () => {
      try {
        const risks = await SafetyRiskPointAPI.getList();
        setAvailableRisks(Array.isArray(risks.data) ? risks.data : []);
      } catch (error) {
        toast({
          variant: "destructive",
          title: "错误",
          description: "无法加载风险点数据",
        });
      }
    };
    loadRisks();
  }, [toast]);

  useEffect(() => {
    const initialTemplate = template
      ? {
          ...template,
          documentTemplateId: template.documentTemplateId || null,
          commonEmergencyMeasureIds: Array.isArray(
            template.commonEmergencyMeasureIds
          )
            ? template.commonEmergencyMeasureIds
            : [],
        }
      : {
          methodCode: generateMethodCode(),
          methodName: "",
          description: "",
          applicableScenarios: [],
          compilationBasisIds: [],
          commonEmergencyMeasureIds: [],
          constructionSteps: [],
          commonEmergencyMeasures: [],
          engineeringFactors: {},
          powerOutageScopeTemplate: "",
          groundingWirePositionsTemplate: [],
          liveCrossingSafetyMeasuresTemplate: [],
          coordinationDepartmentsTemplate: [],
          emergencyContactInfoTemplate: {
            dispatcherPhone: "",
            emergencyRepairPhone: "",
            projectManagerPhone: "",
            safetySupervisorPhone: "",
          },
          documentTemplateId: null,
        };

    if (initialTemplate.constructionSteps) {
      initialTemplate.constructionSteps = initialTemplate.constructionSteps.map(
        (step) => ({
          ...step,
          standardWorkCategories: Array.isArray(step.standardWorkCategories)
            ? step.standardWorkCategories
            : [],
          associatedRiskCodes: Array.isArray(step.associatedRiskCodes)
            ? step.associatedRiskCodes
            : [],
          technicalMeasures: Array.isArray(step.technicalMeasures)
            ? step.technicalMeasures
            : [],
          safetyMeasures: Array.isArray(step.safetyMeasures)
            ? step.safetyMeasures
            : [],
          qualityMeasures: Array.isArray(step.qualityMeasures)
            ? step.qualityMeasures
            : [],
          environmentalMeasures: Array.isArray(step.environmentalMeasures)
            ? step.environmentalMeasures
            : [],
          requiredMaterials: Array.isArray(step.requiredMaterials)
            ? step.requiredMaterials
            : [],
          requiredPersonnel: Array.isArray(step.requiredPersonnel)
            ? step.requiredPersonnel
            : [],
          requiredEquipment: Array.isArray(step.requiredEquipment)
            ? step.requiredEquipment
            : [],
          requiredVehicles: Array.isArray(step.requiredVehicles)
            ? step.requiredVehicles
            : [],
        })
      );
    } else {
      initialTemplate.constructionSteps = [];
    }

    if (
      !initialTemplate.engineeringFactors ||
      typeof initialTemplate.engineeringFactors !== "object"
    ) {
      initialTemplate.engineeringFactors = {};
    }

    setLocalTemplate(initialTemplate);
  }, [template]);

  useEffect(() => {
    const fetchRelatedData = async () => {
      try {
        const [standardsData, docTemplatesData, emergencyMeasureTemplateData] =
          await Promise.all([
            StandardAPI.getList(),
            DocumentTemplateAPI.getList(),
            EmergencyMeasureTemplateAPI.getList(),
          ]);
        setAllStandards(standardsData.data || []);
        setDocumentTemplates(docTemplatesData.data || []);
        setEmergencyMeasureTemplate(emergencyMeasureTemplateData.data || []);
      } catch (error) {
        console.error("Failed to fetch related data:", error);
      }
    };
    fetchRelatedData();
  }, []);

  useEffect(() => {
    if (documentTemplates.length > 0 && template?.documentTemplateId) {
      setLocalTemplate((prevLocalTemplate) => {
        if (
          prevLocalTemplate.documentTemplateId !== template.documentTemplateId
        ) {
          return {
            ...prevLocalTemplate,
            documentTemplateId: template.documentTemplateId,
          };
        }
        return prevLocalTemplate;
      });
    }
  }, [documentTemplates, template]);

  const tertiaryToPrimaryMap = useMemo(() => {
    const map = new Map();
    if (!Array.isArray(availableRisks)) {
      console.warn("availableRisks不是有效的数组");
      return map;
    }

    availableRisks.forEach((risk, index) => {
      if (!risk || !risk.tertiaryCategory || !risk.primaryCategory) {
        console.warn(`风险点数据不完整，索引: ${index}`, risk);
        return;
      }

      if (!map.has(risk.tertiaryCategory)) {
        map.set(risk.tertiaryCategory, risk.primaryCategory);
      }
    });

    return map;
  }, [availableRisks]);

  const handleFieldChange = useCallback((field, value) => {
    setLocalTemplate((prev) => ({ ...prev, [field]: value }));
  }, []);

  const handleConstructionStepsUpdate = useCallback(
    (value) => {
      handleFieldChange("constructionSteps", value);
    },
    [handleFieldChange]
  );

  const handleEngineeringFactorsUpdate = useCallback(
    (value) => {
      handleFieldChange("engineeringFactors", value);
    },
    [handleFieldChange]
  );

  const handleScenarioChange = useCallback((scenarioCode, isChecked) => {
    setLocalTemplate((prev) => {
      const currentScenarios = prev.applicableScenarios || [];
      if (isChecked) {
        return {
          ...prev,
          applicableScenarios: [...currentScenarios, scenarioCode],
        };
      } else {
        return {
          ...prev,
          applicableScenarios: currentScenarios.filter(
            (s) => s !== scenarioCode
          ),
        };
      }
    });
  }, []);

  const handleBasisChange = useCallback((standardId, isChecked) => {
    setLocalTemplate((prev) => {
      const currentBasis = prev.compilationBasisIds || [];
      if (isChecked) {
        return {
          ...prev,
          compilationBasisIds: [...currentBasis, standardId],
        };
      } else {
        return {
          ...prev,
          compilationBasisIds: currentBasis.filter((id) => id !== standardId),
        };
      }
    });
  }, []);

  const handleEmergencyMeasureChange = useCallback((measureId, isChecked) => {
    setLocalTemplate((prev) => {
      const currentIds = prev.commonEmergencyMeasureIds || [];
      if (isChecked) {
        if (!currentIds.includes(measureId)) {
          return {
            ...prev,
            commonEmergencyMeasureIds: [...currentIds, measureId],
          };
        }
      } else {
        return {
          ...prev,
          commonEmergencyMeasureIds: currentIds.filter(
            (id) => id !== measureId
          ),
        };
      }
      return prev;
    });
  }, []);

  const handleEmergencySelectAll = useCallback(() => {
    setLocalTemplate((prev) => {
      const currentIds = prev.commonEmergencyMeasureIds || [];
      const allMeasureIds = emergencyMeasureTemplate.map((item) => item.id);
      return {
        ...prev,
        commonEmergencyMeasureIds:
          currentIds.length === allMeasureIds.length ? [] : allMeasureIds,
      };
    });
  }, [emergencyMeasureTemplate]);

  const handleSubmit = useCallback(
    (e) => {
      e.preventDefault();

      const completeTemplateData = {
        ...localTemplate,
        engineeringFactors: localTemplate.engineeringFactors || {
          spanFactorRules: [],
          heightFactorRules: [],
          nettingFactorRules: [],
          angleFactorRules: [],
          widthFactorRules: [],
          typeFactorMultipliers: [],
        },
      };

      onSubmit(completeTemplateData);
    },
    [localTemplate, onSubmit]
  );

  const scenarios = [
    { code: "highway", label: "高速公路" },
    { code: "roadsOrdinary", label: "普通公路(封路)" },
    { code: "electricPowerCircuit", label: "电力线路(停电)" },
    { code: "powerLinesWithoutPowerOutage", label: "电力线路(不停电)" },
    { code: "railwayOrdinary", label: "普通铁路" },
    { code: "riverWay", label: "通航河流" },
    { code: "others", label: "其他" },
  ];

  return (
    <Card className="mb-6 shadow-lg border-blue-200" id="method-template-form">
      <CardHeader className="bg-blue-50">
        <CardTitle className="flex items-center justify-between">
          <span className="flex items-center gap-2">
            <Settings className="w-5 h-5 text-blue-600" />
            {template
              ? `编辑施工方法: ${template.methodName}`
              : "新建施工方法模板"}
          </span>
          <Button 
            type="button"
            variant="ghost" 
            size="icon" 
            onClick={onCancel}
          >
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>
      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          <Tabs defaultValue="basic" className="w-full">
            <TabsList className="grid w-full grid-cols-5">
              <TabsTrigger value="basic">基本信息</TabsTrigger>
              <TabsTrigger value="basis">编制依据</TabsTrigger>
              <TabsTrigger value="steps">施工步骤</TabsTrigger>
              <TabsTrigger value="factors">工程系数</TabsTrigger>
              <TabsTrigger value="emergency">应急措施</TabsTrigger>
            </TabsList>

            {/* 基本信息 */}
            <TabsContent value="basic" className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium mb-1">
                    方法名称
                  </label>
                  <Input
                    value={localTemplate.methodName || ""}
                    onChange={(e) =>
                      handleFieldChange("methodName", e.target.value)
                    }
                    placeholder="例如: 无人机牵引施工法"
                    required
                  />
                </div>
                {/* 方法代码输入框已被移除 */}
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">
                  方法描述
                </label>
                <AutoResizingTextarea
                  value={localTemplate.description || ""}
                  onChange={(e) =>
                    handleFieldChange("description", e.target.value)
                  }
                  placeholder="详细描述该施工方法的特点、适用范围等"
                  minRows={4}
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">
                  适用场景
                </label>
                <div className="flex flex-wrap gap-3 p-3 bg-gray-50 rounded-lg border">
                  {scenarios.map((scenario) => (
                    <div
                      key={scenario.code}
                      className="flex items-center gap-2"
                    >
                      <input
                        type="checkbox"
                        id={`scenario-${scenario.code}`}
                        checked={(
                          localTemplate.applicableScenarios || []
                        ).includes(scenario.code)}
                        onChange={(e) =>
                          handleScenarioChange(scenario.code, e.target.checked)
                        }
                        className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <label
                        htmlFor={`scenario-${scenario.code}`}
                        className="text-sm"
                      >
                        {scenario.label}
                      </label>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">
                  默认文档模板 (可选)
                </label>

                <Select
                  value={localTemplate.documentTemplateId}
                  onValueChange={(value) =>
                    handleFieldChange("documentTemplateId", value)
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="为此施工方法选择一个默认的文档模板" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={null}>无</SelectItem>
                    {documentTemplates.map((dt) => (
                      <SelectItem key={dt.id} value={dt.id}>
                        {dt.name} (v{dt.version})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="text-xs text-gray-500 mt-1">
                  当在创建施工方案时选择此方法，将自动关联这个文档模板。
                </p>
              </div>
            </TabsContent>

            {/* 编制依据 */}
            <TabsContent value="basis">
              <div className="space-y-4">
                <h3 className="text-lg font-semibold flex items-center gap-2">
                  <BookText className="w-5 h-5 text-green-600" />
                  关联标准规范
                </h3>
                <div className="max-h-96 overflow-y-auto p-4 bg-gray-50 rounded-lg border space-y-3">
                  {allStandards.length > 0 ? (
                    allStandards.map((standard) => (
                      <div
                        key={standard.id}
                        className="flex items-center gap-3 p-2 bg-white rounded-md border"
                      >
                        <input
                          type="checkbox"
                          id={`standard-${standard.id}`}
                          checked={(
                            localTemplate.compilationBasisIds || []
                          ).includes(standard.id)}
                          onChange={(e) =>
                            handleBasisChange(standard.id, e.target.checked)
                          }
                          className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 shrink-0"
                        />
                        <label
                          htmlFor={`standard-${standard.id}`}
                          className="flex-1 cursor-pointer"
                        >
                          <p className="font-medium text-sm text-gray-800">
                            {standard.name}
                          </p>
                        </label>
                      </div>
                    ))
                  ) : (
                    <div className="text-center py-4 text-gray-500">
                      <p>暂无可用标准规范，请先在后台录入。</p>
                    </div>
                  )}
                </div>
              </div>
            </TabsContent>

            {/* 施工步骤 */}
            <TabsContent value="steps">
              <ConstructionStepsEditor
                steps={localTemplate.constructionSteps || []}
                onUpdate={handleConstructionStepsUpdate}
                availableRisks={availableRisks}
              />
            </TabsContent>

            {/* 工程系数 */}
            <TabsContent value="factors">
              <EngineeringFactorsEditor
                factors={localTemplate.engineeringFactors || {}}
                onUpdate={handleEngineeringFactorsUpdate}
              />
            </TabsContent>

            {/* 应急措施 */}
            <TabsContent value="emergency">
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3
                    className="text-lg font-semibold flex items-center gap-2"
                  >
                    <Shield className="w-5 h-5 text-orange-600" />
                    关联应急措施
                  </h3>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      handleEmergencySelectAll();
                    }}
                    disabled={emergencyMeasureTemplate.length === 0}
                    className="h-8 px-3"
                  >
                    {localTemplate.commonEmergencyMeasureIds?.length ===
                    emergencyMeasureTemplate.length
                      ? "取消全选"
                      : "全选"}
                  </Button>
                </div>
                <div className="max-h-96 overflow-y-auto p-4 bg-gray-50 rounded-lg border space-y-3">
                  {emergencyMeasureTemplate.length > 0 ? (
                    emergencyMeasureTemplate.map((measure) => (
                      <div
                        key={measure.id}
                        className="flex items-center gap-3 p-2 bg-white rounded-md border"
                      >
                        <input
                          type="checkbox"
                          id={`emergency-${measure.id}`}
                          checked={(
                            localTemplate.commonEmergencyMeasureIds || []
                          ).includes(measure.id)}
                          onChange={(e) =>
                            handleEmergencyMeasureChange(
                              measure.id,
                              e.target.checked
                            )
                          }
                          className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 shrink-0"
                        />
                        <label
                          htmlFor={`emergency-${measure.id}`}
                          className="flex-1 cursor-pointer"
                        >
                          <p className="font-medium text-sm text-gray-800">
                            {measure.incidentType || measure.name}
                          </p>
                          {measure.code && (
                            <p className="text-xs text-gray-500">
                              {measure.code}
                            </p>
                          )}
                        </label>
                      </div>
                    ))
                  ) : (
                    <div className="text-center py-4 text-gray-500">
                      <p>暂无可用应急措施，请先在后台录入。</p>
                    </div>
                  )}
                </div>

                {emergencyGenResult && (
                  <div className="text-sm text-gray-600 bg-gray-100 px-3 py-2 rounded mt-2">
                    {emergencyGenResult}
                  </div>
                )}
              </div>
            </TabsContent>
          </Tabs>

          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button type="button" variant="outline" onClick={onCancel}>
              <X className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button type="submit" className="bg-blue-600 hover:bg-blue-700">
              <Save className="w-4 h-4 mr-2" />
              保存模板
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}